<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Controller;

/**
 * Description of MwsStockController
 *
 * @author zhouyehao
 */
class MwsStockController extends AdminController {

    protected $model = null;
    //当前登录管理员所有子节点组别
    protected $childrenIds = [];
    protected $serviceUrl = "https://mws.amazonservices.com/FulfillmentInventory/2010-10-01";
    protected $awsAccessKeyId = 'AKIAJV6ZBRFUMZR4PQBA';
    protected $sellerId = 'AFM3VFC9BYR23';
    protected $secretKey = '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';
    protected $marketplaceId = 'ATVPDKIKX0DER';
    protected $applicationName = 'XiangKe';
    protected $applicationVersion = '1.0';
    protected $mwsConfig = array(
        'ServiceURL' => 'https://mws.amazonservices.com/FulfillmentInventory/2010-10-01',
        'ProxyHost' => null,
        'ProxyPort' => -1,
        'ProxyUsername' => null,
        'ProxyPassword' => null,
        'MaxErrorRetry' => 3,
    );

// More endpoints are listed in the MWS Developer Guide
// North America:
//$serviceUrl = "https://mws.amazonservices.com/FulfillmentInventory/2010-10-01";
// Europe
//$serviceUrl = "https://mws-eu.amazonservices.com/FulfillmentInventory/2010-10-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/FulfillmentInventory/2010-10-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/FulfillmentInventory/2010-10-01";

    public function _initialize() {
        vendor('FBAInventoryServiceMWS.Samples.config', '', '.php');

        parent::_initialize();
    }

    public function test() {
//        $date_time = date('Y-m-d H:i:s',time());
//        $queryStartDateTime = gmdate("Y-m-d\TH:i:s\Z", strtotime($date_time));
//        $token = 'H4sIAAAAAAAAADXQy46CMABA0V8xZFx1AW1QIRkmgYIMEAVFUNjVCFTb+qrI4+vHzdzlWd7vszyySXd6WkpNuKyUiXhZyvRr+qvLwP7P38dD93BXjrNU5w0jrFu38dndcEADjLjoQ62PPBIUM1MrwLu9hx+s23fZ53tQFpzmhcZwgl4oXew8sDKOvDwkWbjIRjeHcFfSC2nos4IaaSSPzJG1cVLhwB7YaFIG1w837V4XcvJQvqwbyK9ySHV2x1WZhWB2O24Dw0Z9Ed2GUY9dYGBk+Dd/vLZSz4TqYy0Vl4Dqc3oQJyHZQsCmGxI1dOHdcEQNzQSE/kZDgkmHJz3YEmBHcONcddx4nwGWpag/f7dH6h0sAQAA_mEaNrCkReYPtTpElDaMcKeP_ATVPDKIKX0DER';
//        $nextToken ='H4sIAAAAAAAAADXPyXKCMAAA0F9xmHryAAMJy0zpTEFIUokoq/EmLlRWKwGEr28vfX/w3u9dVi7Gy9MUbqequwqLmpvC8m2JQUc+/6HUT8fe3lu2K0LcPWs5s2coEfa9IXmll1KCsfs4pPTSG/7Wa9So1o98XvOVzF/JSQZ2YfnFdVX36qDvj0x8gYmqWmgZNFCa0KmODFEvhQFfO2iKyPlcQeDtXBWxINowTrT8brQgHc4XvlfAISi9R0zqKrGoOtw2sYuaFflilMvspTfrLA20K2YFHLc+cJCILClEjz7Uo7D1XAVWWSO347QbizKLWvoUNWj/cDc+9VMtzRjiQs2biBh27vzlTVMQP34BOS0oeSgBAAA=_mEaNrCkReYPtTpElDaMcKeP_ATVPDKIKX0DER';
////        $test = $this->getNextSkuStock($token);
//        
//        while ($nextToken) {
//                echo 123;die;
//                $next = $this->getNextSkuStock($nextToken);
//                $nextData = $next['ListInventorySupplyByNextTokenResult']['InventorySupplyList'];
//                $num += $this->saveStock($nextData);
//                if (isset($next['ListInventorySupplyByNextTokenResult']['NextToken'])) {
//                    $nextToken = $next['ListInventorySupplyByNextTokenResult']['NextToken'];
//                } else {
//                    $nextToken = '';
//                }
//        }
//        echo 222;die;
        $test = $this->getMwsStock();
        dump($test);
        die;

//        $date = 
//        dump($this->getOrderList($date));
    }

    private function invokeData(\FBAInventoryServiceMWS_Interface $service, $request, $action) {
        try {
            $response = $service->$action($request);
            return $response;
        } catch (\FBAInventoryServiceMWS_Exception $ex) {
            dump($ex);
            return FALSE;
        }
    }

    public function getMwsStock() {
        $date_time = I('query_date_time');

        if (empty($date_time)) {
            $date_time = date('Y-m-d H:i:s', time() - 3600 * 24);
        }

        $queryStartDateTime = gmdate("Y-m-d\TH:i:s\Z", strtotime($date_time));

        $data = $this->getSkuStock($queryStartDateTime);
       
        if (!empty($data)) {
            $num = 0;
            $nextToken = '';
            if (isset($data['ListInventorySupplyResult']['NextToken'])) {
                $nextToken = $data['ListInventorySupplyResult']['NextToken'];
            }
//            dump($nextToken);die;
            $fristData = $data['ListInventorySupplyResult']['InventorySupplyList'];
            $num = $this->saveStock($fristData);
            while ($nextToken) {
                $next = $this->getNextSkuStock($nextToken);
                $nextData = $next['ListInventorySupplyByNextTokenResult']['InventorySupplyList'];
                $num += $this->saveStock($nextData);
                if (isset($next['ListInventorySupplyByNextTokenResult']['NextToken'])) {
                    $nextToken = $next['ListInventorySupplyByNextTokenResult']['NextToken'];
                } else {
                    $nextToken = '';
                }
            }

            if ($num) {
                $this->ajaxSuccess('成功获取' . $num . '条数据');
            }
        }
        $this->ajaxError('获取失败');
    }

    public function getSkuStock($queryStartDateTime) {
        vendor('FBAInventoryServiceMWS.Client', '', '.php');
        vendor('FBAInventoryServiceMWS.Model.ListInventorySupplyRequest', '', '.php');
        $service = new \FBAInventoryServiceMWS_Client($this->awsAccessKeyId, $this->secretKey, $this->mwsConfig, $this->applicationName, $this->applicationVersion);
        $request = new \FBAInventoryServiceMWS_Model_ListInventorySupplyRequest();

//        $request->setSellerSkus('A311_Silver_S');
        $request->setMarketplaceId($this->marketplaceId);
        $request->setQueryStartDateTime($queryStartDateTime);
//        $request->setMWSAuthToken($this->awsAccessKeyId);
        $request->setSellerId($this->sellerId);

        $xmlinfo = $this->invokeData($service, $request, 'ListInventorySupply');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    /**
     * 获取下一页
     */
    public function getNextSkuStock($nextToken) {

        vendor('FBAInventoryServiceMWS.Client', '', '.php');
        vendor('FBAInventoryServiceMWS.Model.ListInventorySupplyByNextTokenRequest', '', '.php');
        $service = new \FBAInventoryServiceMWS_Client($this->awsAccessKeyId, $this->secretKey, $this->mwsConfig, $this->applicationName, $this->applicationVersion);
        $request = new \FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest();
        $request->setSellerId($this->sellerId);
        $request->setNextToken($nextToken);
//        dump($request);die;
        $xmlinfo = $this->invokeData($service, $request, 'ListInventorySupplyByNextToken');
        if ($xmlinfo) {
            $list = $this->xmlToArray($xmlinfo);
//            Log::write($list, 'info', true);
            return $list;
        } else {
            return [];
        }
    }

    //xml转换成数组
    public function xmlToArray($data) {
        return json_decode(json_encode((array) simplexml_load_string($data)), true);
    }

    //美国时间转换成中国时间
    public function usaDateToCn($date) {
        return date('Y-m-d H:i:s', strtotime($date));
    }

    public function saveStock($data) {
        $skus = $data['member'];

        $num = 0;
        foreach ($skus as $val) {
            M()->startTrans();
            try {
                $asin = $val['ASIN'];
                $res = M('MwsSku')->where(array('ASIN' => $asin))->find();
                $val = $this->formatStock($val);
                if ($res) {
                    unset($val['ASIN']);
                    unset($val['SellerSKU']);
                    unset($val['FNSKU']);
                    $val['updatetime'] = date('Y-m-d H:i:s', time());
                    M('MwsSku')->where(array('ASIN' => $asin))->save($val);
                } else {
                    M('MwsSku')->add($val);
                    $num++;
                }
                M()->commit();
            } catch (\Exception $e) {
                // 回滚事务
                M()->rollback();
                return 0;
            }
        }
        return $num;
    }

    public function formatStock($skus) {
        if (empty($skus)) {
            return [];
        }
        $tmp = [];

        $tmp['seller_sku'] = $skus['SellerSKU'];
        $tmp['ASIN'] = $skus['ASIN'];
        $tmp['FNSKU'] = $skus['FNSKU'];
        $tmp['in_stock_supply_quantity'] = $skus['InStockSupplyQuantity'];
        $tmp['total_supply_quantity'] = $skus['TotalSupplyQuantity'];

        return $tmp;
    }

}
